import com.alibaba.fastjson.JSONObject;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @ClassName: HelloIOpenHtmlToPdf
 * @Author: liugui
 * @Date: 2022-04-20 13:21
 **/
public class HelloIOpenHtmlToPdf {
    /**
     * demo 中文问题待解决
     * @param args
     */
    public static void main(String[] args) {
        TemplateEngine templateEngine = new TemplateEngine();
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("templates/");//指定模版前缀，即存放位置，默认是该地址
        templateResolver.setSuffix(".html");//指定模版后缀
        templateResolver.setTemplateMode(TemplateMode.HTML);//指定使用‘XML’模式
        templateResolver.setCharacterEncoding("UTF-8");//指定使用‘UTF-8’编码
        templateResolver.setCacheable(false);//开启缓存
        templateEngine.setTemplateResolver(templateResolver);
        Context ctx = new Context(Locale.getDefault());
        try {
            // data
            PoPurd poPurd = new PoPurd();
            poPurd.setSupId("供应商demo");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("demo1","1");
            Map<String,Object> map = new HashMap<>();
            map.put("demo","hello openhtmltopdf");
            map.putAll(jsonObject);
            ctx.setVariables(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String htmlContent = templateEngine.process("demo", ctx);
        OutputStream os = null;
        try {
            os = new FileOutputStream("F:\\demo.pdf");
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.useFastMode();
            builder.withHtmlContent(htmlContent, ResourceUtils.getURL("classpath:").toExternalForm());
            builder.toStream(os);
            builder.run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

class PoPurd{

    public PoPurd() {
    }

    private String supId;

    public void setSupId(String supId) {
        this.supId = supId;
    }
}

